package com.ysh.mybatis.utiles;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * 袁胜虎 on 2022/8/24 11:22
 */
public class MyBatisUtil {
    private static ThreadLocal<SqlSession>threadLocal=new ThreadLocal<>();

    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取连接
     * @return
     */
    private static SqlSession openSession(){
        //创建并保存到threadlocal
        SqlSession sqlSession = sqlSessionFactory.openSession();
        threadLocal.set(sqlSession);
        return sqlSession;
    }

    /**
     * 提交事务
     */
    public static void commit(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null){
            sqlSession.commit();
        }
    }
    /**
     * 回滚事务
     */
    public static void rollback(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null){
            sqlSession.rollback();
        }
    }
    /**
     * 关闭连接
     */
    public  static void close(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null){
            sqlSession.close();
            //移除,移除后防止内存泄露
            threadLocal.remove();
        }
    }
    /**
     * 获取mapper对象
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T>T getMapper(Class<T>clazz){
        SqlSession sqlSession = threadLocal.get();
        //没有的情况下创建
        if (sqlSession == null){
            sqlSession = openSession();
        }
        //返回mapper
        return  sqlSession.getMapper(clazz);
    }
}
